package com.controller;

import com.alibaba.excel.EasyExcel;
import com.annotation.IgnoreAuth;
import com.entity.AwardCaseEntity;
import com.entity.vo.AwardCaseVo;
import com.entity.vo.ContestCreditsVo;
import com.service.impl.AwardCaseServiceImpl;
import com.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author mgl
 * @version 1.0
 * @description 获奖情况控制器
 * @date 2024/4/10 15:39
 */
@RestController
@RequestMapping("/award")
@Api
public class AwardCaseController {

    @Autowired
    private AwardCaseServiceImpl awardCaseService;

//    @GetMapping("/list")
    @ApiOperation("根据学生id 查找所有获奖信息(数组) studentId不传代表获取所有获奖信息 返回字段参考AwardCaseVo")
    @Deprecated
    public R list__(@ApiParam @RequestParam(value = "studentId", required = false) Integer studentId,
                  @RequestParam(value = "studentName", required = false) String studentName,
                  @RequestParam(value = "contestName", required = false)String contestName,
                  @RequestParam(value = "page", required = false) Integer pageNo,
                  @RequestParam(value = "limit", required = false) Integer pageSize,
                  HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        map.put("studentName", studentName);
        map.put("contestName", contestName);
        int length;
        if (studentId == null){
            length = awardCaseService.selectAll(map).size();
        }else {
            length = awardCaseService.selectByStudentId(studentId, map).size();
        }
        if (request.getSession().getAttribute("role").equals("教师")) {
            map.put("teacherId", request.getSession().getAttribute("userId"));
        } else if (request.getSession().getAttribute("role").equals("管理员")) {
            map.put("adminId", request.getSession().getAttribute("userId"));
        }
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        if(pageNo == null || pageSize == null) {
            map.put("pageSize", null);
            map.put("begin", null);
        } else {
            map.put("pageSize", pageSize);
            map.put("begin", (pageNo - 1) * pageSize);
        }

        if (studentId == null){
            return R.ok().put("data", awardCaseService.selectAll(map)).put("length",length);
        }

        return R.ok().put("data", awardCaseService.selectByStudentId(studentId, map)).put("length", length);
    }

    @GetMapping("/list")
    public R list(@ApiParam @RequestParam(value = "studentId", required = false) Integer studentId,
                    @RequestParam(value = "studentName", required = false) String studentName,
                    @RequestParam(value = "contestName", required = false)String contestName,
                    @RequestParam(value = "page", required = false) Integer pageNo,
                    @RequestParam(value = "limit", required = false) Integer pageSize,
                    @RequestParam(value = "status", required = false) List<Integer> status,
                    HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        map.put("studentName", studentName);
        map.put("contestName", contestName);

        // 这个status是判断一些状态的信息 -1 0 1 2
        if (status == null || status.isEmpty()) map.put("status", null);
        else map.put("status", status);


        //先获取角色信息
        String role = (String) request.getSession().getAttribute("role");
        Long userId = (Long) request.getSession().getAttribute("userId");

        if (role.equals("学生")) map.put("studentId", userId);
        else if (role.equals("教师")) map.put("teacherId", userId);
        else map.put("adminId", userId);

        // 这里要先查询一次了
        int length = awardCaseService.selectListModified(map).size();

        if(pageNo == null || pageSize == null) {
            map.put("pageSize", null);
            map.put("begin", null);
        } else {
            map.put("pageSize", pageSize);
            map.put("begin", (pageNo - 1) * pageSize);
        }

        //添加分页条件后再查询一次
        return R.ok().put("data", awardCaseService.selectListModified(map)).put("length", length);
    }

    @PostMapping("/update")
    @ApiOperation("根据id修改 获奖信息 比如审核通过 或者学生自行修改自己的申请信息 传参数时参考AwardCaseEntity")
    public R update(@RequestBody AwardCaseEntity awardCase) {
        awardCaseService.updateById(awardCase);
        return R.ok();
    }

    @PostMapping("/add")
    @ApiOperation("学生新建一个获奖申请 传的参数参考AwardCaseEntity")
    public R add(@RequestBody AwardCaseEntity awardCase) {
        awardCaseService.insert(awardCase);
        return R.ok();
    }

    @GetMapping("/delete")
    @ApiOperation("根据id删除一条信息")
    public R delete(@ApiParam @RequestParam("ids") List<Integer> ids) {
        awardCaseService.deleteBatchIds(ids);
        return R.ok();
    }

    @GetMapping("/exportExcel")
    @ApiOperation("导出Excel studentId传的话导出的是对应自己学生id的")
    @IgnoreAuth
    public void getExcel(@ApiParam @RequestParam(value = "studentId", required = false) Integer studentId,
                      HttpServletResponse response, HttpServletRequest request) throws IOException {
        Map<String,Object> map = new HashMap<>();
        List<Integer> status = new ArrayList<>();
        status.add(2);
        map.put("studentId", studentId);
        map.put("status", status);
        if (request.getSession().getAttribute("role").equals("教师"))
            map.put("teacherId", request.getSession().getAttribute("userId"));

        List<AwardCaseVo> list = awardCaseService.selectListModified(map);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("result", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), AwardCaseVo.class).sheet("sheet").doWrite(list);
    }

    @PostMapping("/audit")
    public R audit(@RequestBody AwardCaseEntity awardCase, HttpServletRequest request) {
        if (request.getSession().getAttribute("role").equals("管理员")) {

            if (awardCase.getStatus() == 1) awardCase.setStatus(2);  //管理端审核通过 状态为2
            else awardCase.setStatus(-1);

        }else if (request.getSession().getAttribute("role").equals("教师")) {
            if (awardCase.getStatus() == 1) awardCase.setStatus(1); // 教师端审核通过 进入管理员审核 对应状态为1
            else awardCase.setStatus(-1); //审核驳回均返回 -1
        }

        awardCaseService.updateById(awardCase);
        return R.ok();
    }

    @ApiOperation("无用接口  为了展示一个实体类AwardCaseVo的字段信息")
    @GetMapping("/test2")
    public R test2(@RequestBody AwardCaseVo awardCaseVo) {
        return R.ok();
    }

}
